<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('投资主体')" prop="investmentId">
            <el-select v-model="form.investmentId" :placeholder="$t('投资主体')">
              <el-option
                v-for="investment in investmentList"
                :key="investment.id"
                :label="investment.investorName"
                :value="investment.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('投资本金') + $t('金额单位')" prop="amount">
            <money v-model="form.amount" unit="w" :placeholder="$t('投资本金')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('起息日')" prop="valueDate">
            <DatePicker v-model="form.valueDate" :placeholder="$t('起息日')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('到期日')" prop="maturityDate">
            <DatePicker v-model="form.maturityDate" :placeholder="$t('到期日')" @change="dateChange(form.valueDate, form.maturityDate)" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('年利率(%)')" prop="interestRate">
            <Money v-model="form.interestRate" :placeholder="$t('年利率(%)')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('计息天数')" prop="interestDay">
            <dictSelect
              v-model="form.interestDay"
              :clearable="true"
              dictionary="interest_days"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('还款方式')" prop="reimbursementMeans">
            <dictSelect
              v-model="form.reimbursementMeans"
              :clearable="true"
              dictionary="reimbursement_means"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="reimbursementLabel + $t('频率')" prop="repaymentFrequency">
            <dictSelect
              v-model="form.repaymentFrequency"
              :clearable="true"
              dictionary="reimbursement_frequency"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="form.repaymentFrequency === 'day'" :span="12">
          <el-form-item :label="reimbursementLabel + $t('间隔天数')" prop="repaymentInterval">
            <el-input-number v-model="form.repaymentInterval" :placeholder="reimbursementLabel + $t('间隔天数')" :precision="0" :min="1" />
          </el-form-item>
        </el-col>
        <el-col v-if="form.repaymentFrequency !== 'day' && form.repaymentFrequency !== 'maturing'" :span="12">
          <el-form-item :label="reimbursementLabel + $t('约定日')" prop="repaymentAgreed">
            <el-select v-model="form.repaymentAgreed" :placeholder="reimbursementLabel + $t('约定日')" clearable>
              <el-option
                v-for="dict in agreedOptions"
                :key="dict.value"
                :label="$t(dict.label)"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="form.reimbursementMeans === 'ZYHK'" :span="12">
          <el-form-item :label="$t('收息频率')" prop="interestFrequency">
            <dictSelect
              v-model="form.interestFrequency"
              :clearable="true"
              dictionary="reimbursement_frequency"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="form.interestFrequency === 'day' && form.reimbursementMeans === 'ZYHK'" :span="12">
          <el-form-item :label="$t('收息间隔天数')" prop="interestInterval">
            <el-input-number v-model="form.interestInterval" :placeholder="$t('收息间隔天数')" :precision="0" :min="1" />
          </el-form-item>
        </el-col>
        <el-col v-if="form.interestFrequency !== 'day' && form.interestFrequency !== 'maturing' && form.reimbursementMeans === 'ZYHK'" :span="12">
          <el-form-item :label="$t('收息约定日')" prop="interestAgreed">
            <el-select v-model="form.interestAgreed" :placeholder="$t('收息约定日')" clearable>
              <el-option
                v-for="dict in agreedOptions"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <div class="area-header">
        <span class="area-header-title">{{ $t('还款计划') }}</span>
      </div>
      <el-table :data="form.dealServicingPlanList" class="nowrapTable formTable" border>
        <el-table-column :label="$t('还款类型')" align="center" prop="type">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('还款类型') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'dealServicingPlanList.' + scope.$index + '.type'" :rules="dealServicingPlanListRules.type">
              <dictSelect
                v-model="scope.row.type"
                :clearable="true"
                dictionary="servicing_plan_type"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('计划还款日期')" align="center" prop="expectDate">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('计划还款日期') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'dealServicingPlanList.' + scope.$index + '.expectDate'" :rules="dealServicingPlanListRules.expectDate">
              <DatePicker v-model="scope.row.expectDate" :placeholder="$t('计划还款日期')" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('计划还款金额') + $t('金额单位')" align="center" prop="amountPrincipal">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('计划还款金额') }} {{ $t('金额单位') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'dealServicingPlanList.' + scope.$index + '.expectMoney'" :rules="dealServicingPlanListRules.expectMoney">
              <Money v-model="scope.row.expectMoney" unit="w" />
            </el-form-item>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <el-button @click="cancel">{{ $t("取消") }}</el-button>
      <el-button v-hasPermi="['deal:servicing:edit']" type="primary" @click="createPlan">{{ $t('生成还款计划') }}</el-button>
      <el-button v-hasPermi="['deal:servicing:edit']" type="primary" @click="submitForm">{{ $t("保存") }}</el-button>
    </div>
  </div>
</template>

<script>
    import { saveDealServicing, getDealServicing, createPlan } from '@/api/deal/servicing/dealServicing'
    import { listDealInvestment } from '@/api/deal/investment/dealInvestment'
    export default {
        data() {
            return {
                // 表单参数
                form: {},
                // 遮罩层
                loading: false,
                // 表单校验
                rules: {
                  investmentId: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], amount: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], interestRate: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], interestDay: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], repaymentFrequency: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], repaymentInterval: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], repaymentAgreed: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], interestFrequency: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], interestInterval: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], interestAgreed: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], valueDate: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], maturityDate: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], reimbursementMeans: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ]
                },
                // 还款计划表单校验
                dealServicingPlanListRules: {
                },
                // 项目ID
                dealId: this.$route.query.id,
                // 项目投资主体列表
                investmentList: [],
                // 约定日下拉框
                agreedOptions: [],
                // 还款配置label (还本 or 还款)
                reimbursementLabel: this.$t('还款')
            }
        },
        watch: {
          'form.reimbursementMeans'(value) {
            if (value === 'ZYHK') {
              this.reimbursementLabel = this.$t('还本')
            } else {
              this.reimbursementLabel = this.$t('还款')
            }
          }
        },
        created() {
          listDealInvestment({ 'dealId': this.dealId }).then(response => {
            this.investmentList = response.rows
          })
          // 生成约定还款日数据
          this.createAgreedOptions()
        },
        methods: {
          dateChange(valueDate, maturityDate) {
            if (valueDate >= maturityDate) {
              this.rules.maturityDate = [{ required: true, message: this.$t('到期日必须大于起息日'), trigger: 'blur' }]
              this.form.maturityDate = ''
            }
          },
          // 初始化数据
          init(data) {
              if (data != null && data.id !== undefined) {
                this.loading = true
                getDealServicing(data.id).then(response => {
                    this.form = response.data
                    this.loading = false
                })
              } else {
                  this.reset()
              }
          },
          // 表单重置
          reset() {
              this.form = {
              id: undefined,
              dealId: this.$route.query.id,
              investmentId: undefined,
              amount: undefined,
              interestRate: undefined,
              interestDay: undefined,
              reimbursementMeans: undefined,
              repaymentFrequency: undefined,
              repaymentInterval: undefined,
              repaymentAgreed: undefined,
              interestFrequency: undefined,
              interestInterval: undefined,
              interestAgreed: undefined,
              valueDate: undefined,
              maturityDate: undefined,
              createBy: undefined,
              createTime: undefined,
              updateBy: undefined,
              updateTime: undefined,
              delFlag: undefined
              }
              this.resetForm('form')
          },
          // 取消按钮
          cancel() {
              this.$parent.$parent.formOpen = false
              this.$parent.$parent.reset()
          },
          // 关闭form页面
          closeForm() {
              // 关闭form页面遮罩层
              this.loading = false
              // 关闭form页面
              this.$parent.$parent.formOpen = false
              // 刷新list页面
              this.$parent.$parent.getList()
          },
          /** 提交按钮 */
          submitForm: function() {
            this.dateChange(this.form.valueDate, this.form.maturityDate)
            this.$refs['form'].validate(valid => {
                if (valid) {
                    this.loading = true
                    saveDealServicing(this.form).then(response => {
                        if (response.code === 200) {
                            this.msgSuccess(this.$t('保存成功'))
                            this.closeForm()
                        } else {
                            this.msgError(response.msg)
                        }
                        this.loading = false
                    })
                } else {
                  this.locationError(document)
                }
            })
          },
          // 生成还款计划
          createPlan: function() {
            this.dateChange(this.form.valueDate, this.form.maturityDate)
            this.$refs['form'].validate(valid => {
              if (valid) {
                this.loading = true
                createPlan(this.form).then(response => {
                  if (response.code === 200) {
                    this.form.dealServicingPlanList = response.data
                  } else {
                    this.msgError(response.msg)
                  }
                  this.loading = false
                })
              }
            })
          },
          createAgreedOptions: function() {
            for (let i = 1; i <= 31; i++) {
              var agreed = { value: i, label: (i <= 28 ? i : (i + this.$t('(如当月无{day}日,则默认月末最后一天)', { day: i }))) }
              this.agreedOptions.push(agreed)
            }
          }
        }

    }
</script>
